package com.lideru.backstage.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lideru.backstage.entity.dto.UserDto;
import com.lideru.backstage.handler.NoAuth;
import com.lideru.backstage.utils.JWTUtils;
import com.lideru.backstage.utils.common.Result;
import com.lideru.backstage.entity.User;
import com.lideru.backstage.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


/**
 * @author lideru
 */
@RestController
@RequestMapping("user")

public class UserController {
    @Resource
    UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    @NoAuth
    public Result<?> login(@RequestBody User user){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername,user.getUsername()).eq(User::getPassword,user.getPassword()));
        if (res==null){
            return Result.error("-1","用户名或密码错误！");
        }
        String token = JWTUtils.sign(res);
        System.out.println(token);
        //保存到redis内,下次就直接跳过验证
        UserDto userDto = new UserDto();
        userDto.setAvatar(res.getAvatar());
        userDto.setNickName(res.getNickName());
        userDto.setToken(token);
        System.out.println("token:"+token);
        redisTemplate.opsForValue().set("token_" + token, JSON.toJSONString(res), 7, TimeUnit.DAYS);
        return Result.success(userDto);
    }


    @PostMapping
    public Result<?> save(@RequestBody User user){
        if (user.getPassword()==null){
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();
    }
    @PostMapping("register")
    @NoAuth
    public Result<?> register(@RequestBody User user){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername,user.getUsername()));
        if (res!=null){
            return Result.error("-1","用户名也存在！请更换用户名！");
        }
        user.setAvatar("https://img0.baidu.com/it/u=1733508016,1621304144&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500");
        user.setNickName("没有昵称");
        userMapper.insert(user);
        return Result.success();
    }
    @PutMapping
    public Result<?> update(@RequestBody User user){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", user.getId());
        updateWrapper.set("nick_name", user.getNickName());
        updateWrapper.set("sex", user.getSex());
        updateWrapper.set("address", user.getAddress());
        updateWrapper.set("avatar", user.getAvatar());
        updateWrapper.set("phone", user.getPhone());
        int i = userMapper.update(null, updateWrapper);
        System.out.println(i);
        return Result.success();
    }
    @PutMapping("registeredAuthor")
    public Result<?> registeredAuthor(@RequestBody User user,HttpServletRequest request){
        if (user.getPhone().length()!=11){
            return Result.error("-1","手机号码必须是11位");
        }
        user.setId(JWTUtils.getUserId(request.getHeader("token")));
        user.setRole(1);
        System.out.println(user);
        int i = userMapper.updateById(user);
        System.out.println(i);
        if (i<1){
            return  Result.error("-1","系统出错了！");
        }
        return Result.success();
    }
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id){
        userMapper.deleteById(id);
        return Result.success();
    }
    @PostMapping("/getUserById")
    public Result<?> getById(HttpServletRequest request ){
        User user = userMapper.selectById(JWTUtils.getUserId(request.getHeader("token")));
        if(user!=null){
            user.setPassword(null);
            return Result.success(user) ;
        }

        return Result.error("-1","token错误！");

    }

    @GetMapping
    public Result<?> findPage( @RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10")Integer pageSize,
                               @RequestParam(defaultValue = "") String search){
        return Result.success(userMapper.selectPage(new Page<>(pageNum,pageSize), Wrappers.<User>lambdaQuery().like(User::getNickName,search)));
    }
    @GetMapping("grade")
    public Result<?> findGrade(HttpServletRequest request){
        String token = request.getHeader("token");
        User user = userMapper.selectById(JWTUtils.getUserId(token));
        User res = new User();
        res.setRole(user.getRole());
        return Result.success(res);
    }

    @GetMapping("getUserName/{id}")
    @NoAuth
    public Result<?> getUserName( @PathVariable Long id){
        User user = userMapper.selectById(id);
        User user1 = new User();
        user1.setNickName(user.getNickName());
        return Result.success(user1);
    }
    @GetMapping("editPassword/{password}/{pass}")
    public Result<?> editPassword(@PathVariable String password,@PathVariable String pass,HttpServletRequest request){
        Long userId = JWTUtils.getUserId(request.getHeader("token"));
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId,userId)
                .eq(User::getPassword,password));
        if (res==null){
            return Result.error("-2","修改失败！");
        }
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", userId);
        updateWrapper.set("password", pass);
        int i = userMapper.update(null, updateWrapper);
        if (i>0){
            return Result.success();
        }
        return Result.error("-1","修改失败！");
    }




}
